<template>
  <div class="goods-cate">
    <el-card>
      <div slot="header" class="header">
        <span>商品分类</span>
        <el-button
          size="small"
          type="primary"
          @click="dialogFormVisible = true"
        >
          <span>添加分类</span>
        </el-button>
      </div>
      <el-dialog title="添加分类" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item
            prop="cate"
            label="分类名称"
            :label-width="formLabelWidth"
            class="goodsCate"
            status-icon
            :rules="rules"
          >
            <el-input
              class="ipt"
              size="small"
              v-model="form.cate"
              autocomplete="off"
              placeholder="分类名称"
            ></el-input>
          </el-form-item>
          <div class="switch-box">
            <span>是否启用</span>
            <el-switch
              v-model="value"
              active-color="#13ce66"
              inactive-color="#ff4949"
              >></el-switch
            >
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="goodsLei">确 定</el-button>
        </div>
      </el-dialog>

      <div class="content">
        <!-- 表格 -->
        <el-table class="table" :data="tableData" :style="{ width: w + 'px' }">
          <!-- 序号 -->
          <el-table-column type="index" label="序号"></el-table-column>
          <!-- 分类名称 -->
          <el-table-column label="分类名称">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{ scope.row.cateName }}</span>
              <el-input
                v-else
                type="text"
                size="small"
                v-model="scope.row.cateName"
              ></el-input>
            </template>
          </el-table-column>
          <!-- 是否启用 -->
          <el-table-column label="是否启用">
            <template slot-scope="scope">
              <el-switch
                :disabled="!scope.row.isEdit"
                v-model="scope.row.state"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                :type="scope.row.isEdit ? 'success' : ''"
                @click="handleEdit(scope.row)"
                >{{ scope.row.isEdit ? "完成" : "编辑" }}</el-button
              >
              <el-popconfirm
                @confirm="handleDelete(scope.row)"
                @cancel="$message({ type: 'info', message: '取消删除' })"
                title="这个分类确定删除吗？"
              >
                <el-button
                  class="btn-delete"
                  type="danger"
                  size="mini"
                  slot="reference"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :total="total"
          background
          :currentPage="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
          layout="total,prev, pager, next, jumper"
          class="pagination"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getCateList, editCate, delCate, addCate } from "@/api/goods";
import { goodsLei } from "@/utils/tool";
export default {
  data() {
    return {
      rules: {
        cate: [{ validator: goodsLei, trigger: "blur" }],
      },
      //表格数据
      tableData: [],
      //当前页
      currentPage: 1,
      //每页几条
      pageSize: 3,
      //总页数
      total: 0,
      //table宽度
      w: 0,
      value: true,
      form: {
        cate: "",
      },
      dialogFormVisible: false,
      formLabelWidth: "120px",
    };
  },
  methods: {
    async getData() {
      let res = await getCateList({
        currentPage: this.currentPage,
        pageSize: this.pageSize,
      });
      //解构数据
      let { data, total } = res.data;
      //处理数据
      data.forEach((v) => {
        //如果state值为1 给他赋值true 反之false
        v.state = v.state === 1 ? true : false;
        //新增一个可编辑字段
        v.isEdit = false;
      });
      this.total = total;
      this.tableData = data;
      //如果当前页不等与1 且获取数据为空数组， 就拉取上一页数据
      if (this.currentPage !== 1 && this.tableData.length === 0) {
        this.currentPage -= 1;
        //重新拉取数据
        this.getData();
      }
    },
    // 编辑
    async handleEdit(row) {
      //修改当前行的可编辑状态
      row.isEdit = !row.isEdit;
      // console.log(row);
      //只有两种状态
      if (!row.isEdit) {
        let { id, cateName, state } = row;
        state = state ? 1 : 0;
        let res = await editCate({ id, cateName, state });
        // console.log(res);
        let { code, msg } = res.data;
        if (code == 0) {
          this.$message({
            type: "success",
            message: msg,
          });
        }
      }
    },
    // 删除
    async handleDelete(row) {
      let { id } = row;
      let res = await delCate({ id });
      let { code, msg } = res.data;
      if (code == 0) {
        this.$message({
          type: "success",
          message: msg,
        });
        this.getData();
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      // console.log(val);
      this.getData();
    },
    //设置table宽度
    setTableWidth() {
      this.w = document.body.clientWidth - 280;
    },
    async goodsLei() {
      // console.log(this.form.cate);

      let cateName = this.form.cate;
      let state = this.value ? 1 : 0;
      // console.log(state);
      if (cateName == "") {
        this.$message.error("添加失败，商品名称不能为空!");
      } else {
        this.dialogFormVisible = false;
        this.getData();
      }
      let res = await addCate({ cateName, state });
      // console.log(res);
      let { code, msg } = res.data;
      if (code == 0) {
        this.$message({
          type: "success",
          message: msg,
        });
      }
    },
  },
  created() {
    this.getData();
  },
  //生命周期mounted 操作dom
  mounted() {
    this.setTableWidth();
    window.addEventListener("resize", this.setTableWidth);
  },
  beforeDestroy() {
    //在销毁组件前 把window上挂着的方法也销毁
    window.removeEventListener("resize", this.setTableWidth);
  },
};
</script>

<style lang="scss" scoped>
.ipt {
  width: 300px;
}
.switch-box {
  margin-left: 50px;
  span {
    margin-right: 20px;
  }
}
.pagination {
  margin-top: 20px;
}
.header {
  position: relative;
  .el-button {
    position: absolute;
    right: 50px;
  }
}
.btn-delete {
  margin-left: 10px;
}
</style>